package battle

import (
	"server/game/itypes"
	"server/game/pkg/rank"
	"server/share/config"
	"server/share/define"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/updater"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

/**
 * @name dailyBoss
 * 每日boss
 */

func init() {
	Register(&dailyBoss{})
}

type dailyBoss struct{}

func (this *dailyBoss) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*dailyBoss, *context.Context) interface{})
	return f(this, handle)
}

/**
 * @name getRank
 * @param string uid 对手ID
 * 获取排名
 */

func (this *dailyBoss) GetRank(c *context.Context) interface{} {
	uid := c.GetString("uid")
	if uid == "" {
		return errors.ErrArgEmpty
	}
	reply := map[string]interface{}{}
	var err error
	if reply["rank"], err = rank.ZRank(define.RankNameDailyBoss, 0, uid, false); err != nil {
		return err
	}
	if reply["total"], err = rank.ZCard(define.RankNameDailyBoss, 0); err != nil {
		return err
	}

	return reply
}

/**
 * @name getAllRank
 * 获取前100排名
 */
//
//func (this *dailyBoss) GetAllRank(c *context.Context) interface{} {
//	r, err := rank.ZRange(define.RankNameDailyBoss, 0, 0, 9)
//	if err != nil {
//		return err
//	} else {
//		return r
//	}
//}

/**
 * @name endBattle
 * @param int hp 血量
 * 结束战斗
 */
func (this *dailyBoss) EndBattle(c *context.Context) interface{} {
	hp := c.GetInt64("hp")
	if hp > 3000000 {
		return hp
	}
	dh := itypes.Daily.Handle(c.Player.Updater)
	dv := dh.GetInt64("dailyBoss")
	if hp <= dv {
		return hp
	}
	for k, v := range config.Data.BossReward {
		ik := int64(k)
		if ik > dv && hp >= ik {
			c.Player.AddItems(v.ItemDrop)
		}
	}
	dh.Set("dailyBoss", hp)

	c.Player.Updater.On(updater.EventTypeSuccess, func(u *updater.Updater) bool {
		_ = rank.ZAdd(define.RankNameDailyBoss, 0, u.Uid(), hp)
		return false
	})

	return hp
}

/**
 * @name getReward
 * 领取积分
 */

func (this *dailyBoss) GetReward(c *context.Context) interface{} {
	dh := itypes.Daily.Handle(c.Player.Updater)
	dv := dh.GetInt32("dailyBosddReward")
	hp := dh.GetInt64("dailyBoss")
	if dv > 0 {
		return errors.ErrDataExists
	}
	if hp == 0 {
		return errors.Error("今日未参与战斗")
	}

	data, err := rank.ZRank(define.RankNameDailyBoss, 0, c.Uid(), false)
	if err != nil {
		return err
	}
	sort := int32(data.Rank) + 1
	if sort < 100 {
		for _, v := range config.Data.FirstDailyBossRank {
			if sort >= v.RankStart && sort <= v.RankEnd {
				c.Player.Add(v.ItemDrop, v.Num)
				break
			}
		}
	} else {
		//按伤害量
		for _, v := range config.Data.SecondDailyBossRank {
			if hp >= int64(v.RankStart) && (v.RankEnd == 0 || hp <= int64(v.RankEnd)) {
				c.Player.AddItems(v.ItemDrop)
				break
			}
		}
	}
	dh.Set("dailyBosddReward", 1)
	return true
}
